package com.wanxi.servlet.product;

import com.alibaba.fastjson2.JSONObject;
import com.wanxi.dto.ResultDTO;
import com.wanxi.model.ProductType;
import com.wanxi.service.Impl.ProductServiceImpl;
import com.wanxi.service.ProductService;
import com.wanxi.util.Tool;
import com.wanxi.vo.ProductVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

@WebServlet("/admin/product/add")
public class AddProductServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        乱码处理、传输格式处理
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
//        获取前端传来的值
        String productName=req.getParameter("productName");
        String imageLocation=req.getParameter("imageLocation");
        BigDecimal price= Tool.strToDecimal(req.getParameter("price"));
        Integer enable=Tool.strToInt(req.getParameter("enable"));
        String remark=req.getParameter("remark");
        Integer productTypeID=Tool.strToInt(req.getParameter("productTypeID"));
//        调用service处理
        ProductVO productVO= ProductVO.builder()
                .productName(productName)
                .imageLocation(imageLocation)
                .price(price).enable(enable)
                .remark(remark)
                .productType(ProductType.builder()
                        .id(productTypeID).build())
                .build();
        ProductService productService=new ProductServiceImpl();
        ResultDTO resultDTO= productService.addProduct(productVO);
//        返回值给前端
        resp.getWriter().println(JSONObject.toJSONString(resultDTO));
    }
}
